package utils

import (
	"bytes"
	"fmt"
	"os/exec"
	"strings"
)

func ExecuteScriptSynchronously(command string) (string, error) {
	// 替换多余的空格
	command = replaceMultiSpace(command)

	// 创建 Bash 命令
	cmd := exec.Command("/bin/bash", "-c", command)

	// 捕获标准输出和标准错误
	var outBuf, errBuf bytes.Buffer
	cmd.Stdout = &outBuf
	cmd.Stderr = &errBuf

	// 执行命令并等待完成
	err := cmd.Run()
	fmt.Printf("command: %s\n,err:%s\n,std:%s", command, errBuf.String(), outBuf.String())
	if err != nil {
		// 返回标准错误内容
		//return "", fmt.Errorf("error: %v, stderr: %s", err, errBuf.String())
		//兼容之前的逻辑，标准错误报错
		return fmt.Sprintf("error: %v, stderr: %s", err, errBuf.String()), nil
	}

	// 返回标准输出内容
	return strings.TrimSpace(outBuf.String()), nil
}
func replaceMultiSpace(command string) string {
	return strings.Join(strings.Fields(command), " ")
}

func RunA(cmd *exec.Cmd) (string, error) {
	out, err := cmd.CombinedOutput()
	return string(out), err
}
